import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/normal_text_dialog.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/track/item/business_list_cell.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/animation_dialog.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/search_app_bar2.dart';

import 'api/api_track.dart';
import 'model/fuzzy_company_entity.dart';

class TrackAddPage extends StatefulWidget {
  @override
  _TrackAddPageState createState() => _TrackAddPageState();
}

class _TrackAddPageState extends State<TrackAddPage> {
  Future<ApiResponse<List<FuzzyCompanyEntity>>> _future;

  LoadState _loadState = LoadState.State_None;

  List<FuzzyCompanyEntity> _dataLists = [];

  /// 添加追踪
  Future _addTrack(int position, String companyName, String companyKey) async {
    var response = await ApiTrack.addTrack(
        companyName: companyName, companyKey: companyKey);
    if (response.status == Status.SUCCESS) {
      ToastUtils.show("添加成功");
      setState(() {
        _dataLists.removeAt(position);
      });
      LRouter.navigatorCtx(context).pop(true);
    }
  }

  /// 获取数据
  Future<ApiResponse<List<FuzzyCompanyEntity>>> _getData(
      {String keyword}) async {
    var response = await ApiTrack.getCompanyTrackList<List<FuzzyCompanyEntity>>(
      title: keyword != null ? keyword : "",
    );
    return response;
  }

  FutureBuilder<ApiResponse<List<FuzzyCompanyEntity>>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<List<FuzzyCompanyEntity>>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              List temp = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                _dataLists = (temp ?? []);
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initListView(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _future = _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorType11,
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return SearchAppBarStyle2(
        onSearch: (value) {
          _loadState = LoadState.State_Loading;
          setState(() {
            _future = _getData(keyword: value);
          });
        },
        hintText: "请输入要追踪的企业名称",
        autoFocus: true,
        leading: FlatButton(
            onPressed: () {
              LRouter.navigatorCtx(context).pop();
            },
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            child: Image.asset(
              RPath.imgPath + "icon_nav_back_balck.png",
              fit: BoxFit.contain,
              width: ScreenAdapter.width(30),
              height: ScreenAdapter.height(30),
            )));
  }

  /// 内容体
  Widget _initListView() {
    return Padding(
        padding: EdgeInsets.only(top: ScreenAdapter.height(10)),
        child: ListView.separated(
          physics: BouncingScrollPhysics(),
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            FuzzyCompanyEntity model = _dataLists[index];
            return BusinessListCell(
              data: model,
              onTap: () async {
                var result = await showAnimationDialog(
                    context: context,
                    transitionType: TransitionType.rotation,
                    builder: (context) {
                      return NormalTextDialog(
                        content: "确定添加追踪？",
                      );
                    });
                if (result == AppConstant.DIALOG_ACTION_CONFIRM) {
                  _addTrack(index, model.companyName, model.companyKey);
                }
              },
            );
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType11,
            );
          },
        ));
  }
}
